package com.controller;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * 排他网关
 * @author 123
 *
 */
@RestController
public class ExclusiveGateWayController {

	@Autowired
	private ProcessEngine processEngine;
	
	/**
	 * 部署
	 * @return
	 */
	@GetMapping("sequence/deployGateWay")
	public String deploySequenceFlow(){
		
		InputStream bpmn = this.getClass().getResourceAsStream("/diagrams/exclusiveGateWay.bpmn");
		InputStream png = this.getClass().getResourceAsStream("/diagrams/exclusiveGateWay.png");
		
		Deployment deployment = processEngine.getRepositoryService().createDeployment().name("排他网关")
			.addInputStream("exclusiveGateWay.bpmn", bpmn)//与资源文件名称要一致
			.addInputStream("exclusiveGateWay.png", png)
			.deploy();
		
		System.err.println(deployment.getKey() + "---" + deployment.getName());
		
		return deployment.getId();
	}
	
	/**
	 * 启动流程实例
	 * @return
	 */
	@RequestMapping("sequence/startGateWay")
	public String startSequenceFlow(){
		
		String processDefinitionKey = "exclusiveGateWay";
		
		//正在执行的流程实例和执行对象相关的service
		RuntimeService runtimeService = processEngine.getRuntimeService();
		
		//使用流程定义的key启动流程实例，key对应的是bpmn文件中的id，默认是最新版本的流程启动
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey);
		
		System.out.println(processInstance.getId() + processInstance.getProcessDefinitionId());
		
		return processInstance.getProcessDefinitionId();
	}
	
	/**
	 * 查询当前人的个人任务
	 * @return
	 */
	@RequestMapping("sequence/findGateWayTask")
	public String findGateWayTask(){
		
		String assignee = "小菜";
		
		List<Task> list = processEngine.getTaskService()
		.createTaskQuery()
		.taskAssignee(assignee).list();
		
		if(!CollectionUtils.isEmpty(list)){
			for (Task task : list) {
				System.out.println(task.getAssignee());
				System.out.println(task.getId());
				System.out.println(task.getName());
				System.out.println(task.getExecutionId());
			}
		}
		
		System.out.println("****************");
		
		return list.toString();
	}
	
	/**
	 * 完成我的任务
	 * @return
	 */
	@RequestMapping("sequence/completeGateWayTask")
	public String completeGateWayTask(){
		
		String taskId = "45004";
		
		//完成任务的同时，设置流程变量，使用流程变量来指定完成任务
		Map<String, Object> varMap = new HashMap<String, Object>();
		varMap.put("money", "3000");
		
		processEngine.getTaskService().complete(taskId,varMap);
		
		return "完成任务" + taskId;
	}
	
	
}
